<?php
/*
Copyright (C) 2009 de Flotte Maxence

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
?>
<?php
/**
 ************************
 **** Must be delete ****
 ************************
 */
//Génération d'un ZZG
function genZzG($label,$ZzG) {

	//include './ZzO/std/Boot.php';
	//include './ZzO/std/Main.php';

	//Si le label n'est pas un entier
		if(!is_numeric($label)) {
			$_GET['altPuZZle'] = 'true';
			$_infoLabel['type'] = str_replace(array('{','}'),'',strToLower($label));
			$_infoLabel['user'] = !empty($_SESSION['id'])?$_SESSION['id']:1;
			$_infoLabel['group'] = 1;
			$_infoLabel['id'] = 0;
			$_infoLabel['name'] = '';
			$_infoLabel['dateC'] = time();
			$_infoLabel['dateU'] = time();
			$_infoLabel['userW'] = 1;
			$_infoLabel['groupW'] = 1;
			$_infoLabel['otherW'] = 1;
			$_infoLabel['userR'] = 1;
			$_infoLabel['groupR'] = 1;
			$_infoLabel['otherR'] = 1;
			//Identifiant temporaire ?
				if(empty($_SESSION['tmpId']))
					$_SESSION['tmpId'] = 1;
				else
					$_SESSION['tmpId']++;
				$GLOBALS['tmpId'] = $_SESSION['tmpId'];
		}
	//Si label classique
		else {
			//On récupère les infos du label
				if($GLOBALS['store'] and file_exists('./ZzStore/'.$label.'.php')) {
					$_res = unserialize(file_get_contents('./ZzStore/'.$label.'.php'));
					$_infoLabel['id'] = $label;
					$_infoLabel['name'] = $_res['name'];
					$_infoLabel['type'] = $_res['type'];
					$_infoLabel['dateC'] = $_res['dateC'];
					$_infoLabel['dateU'] = $_res['dateU'];
					$_infoLabel['user'] = $_res['user'];
					$_infoLabel['group'] = $_res['group'];
					$_infoLabel['userR'] = $_res['userR'];
					$_infoLabel['userW'] = $_res['userW'];
					$_infoLabel['groupR'] = $_res['groupR'];
					$_infoLabel['groupW'] = $_res['groupW'];
					$_infoLabel['otherR'] = $_res['otherR'];
					$_infoLabel['otherW'] = $_res['otherW'];
				}
				else {
					$_infoLabel = ZzSQL::queryFirst('SELECT id, dateC, dateU, `type`, name, userR, userW, otherR, otherW, groupR, groupW, user, `group` FROM '.$GLOBALS['prefix'].'label  Where id=?',array($label));
					file_put_contents('./ZzStore/'.$label.'.php',serialize($_infoLabel));
				}

				
				//Si il n'y a pas de réponse on retourne une erreur
					if($_infoLabel == null) {
			//chargement du ZzS
			
						loadZzS('ErrorUnknowLabel');
						exit();
					}
			}
			//On récupère le puZZle
				if($_GET['altPuZZle'] == 'true') {
					$puzzleFileName  = './ZzS/write'.ucfirst($_infoLabel['type']).'.ZzS';
					$genPuzzleFileName  = './ZzS/gen/write'.ucfirst($_infoLabel['type']).'.php';
				}
				else {
					$puzzleFileName  = './ZzS/read'.ucfirst($_infoLabel['type']).'.ZzS';
					$genPuzzleFileName  = './ZzS/gen/read'.ucfirst($_infoLabel['type']).'.php';
				}
				$_infoLabel['puZZleName'] = 'read'.ucfirst($_infoLabel['type']);
				
				if(!file_exists($puzzleFileName)) {
					//plus tard on chargera un ZzS
					//2DO
					loadZzS('ErrorPuZZle');
					exit();
				}
				$_infoLabel['ZzS'] = file_get_contents($puzzleFileName);
				$dir = './ZzG/'.$label;

			//Si le dossier n'existe pas, on le crée
			if(!file_exists($dir))
				mkdir($dir);

				$gen = createStaticpuZZle($_infoLabel);
				file_put_contents($ZzG, $gen);
				//On ajoute le fichier dans le fichier log
					//On creer le fichier log si il n'existe pas & on le récupère dans la variable $tree
						if(!file_exists('./ZzG/tree.log')) {
							$_tree['totalSize'] = 0;
							file_put_contents('./ZzG/tree.log', serialize($_tree));
						}
						else
							$_tree = unserialize(file_get_contents('./ZzG/tree.log'));
				//On  ajoute le nouveau fichier cache
					$fileSize = filesize($ZzG);
					$_tree[$ZzG] = $fileSize;
				//On incremente la taille total
					$_tree['totalSize'] += $fileSize;
				file_put_contents('./ZzG/tree.log', serialize($_tree));


				//On affiche le fichier cache
				include $ZzG;
		
				//Si le fichier lataille de la chache est rop grand, alors on fait le menage
				if($_tree['totalSize'] > $GLOBALS['MaxCacheSize']) {
					include './ZzL/cleanZzG.php';
					cleanZzG();
				}

}

/*function createStaticpuZZle($_label,&$php = null) {
	
	if(empty($_label['group']))
		$_label['group'] = 0;
	if(empty($_label['user']))
		$_label['user'] = 0;
	
	//$ZzS = $_label['ZzS'];
	$GLOBALS['label_user'] = $_label['user'];
	$GLOBALS['label_group'] = $_label['group'];
	$GLOBALS['label_id'] = $_label['id'];
	$GLOBALS['label_name'] = $_label['name'];
	$GLOBALS['label_type'] = $_label['type'];
	$GLOBALS['label_dateC'] = $_label['dateC'];
	$GLOBALS['label_dateU'] = $_label['dateU'];
	$GLOBALS['label_userW'] = $_label['userW'];
	$GLOBALS['label_groupW'] = $_label['groupW'];
	$GLOBALS['label_otherW'] = $_label['otherW'];
	$GLOBALS['label_userR'] = $_label['userR'];
	$GLOBALS['label_groupR'] = $_label['groupR'];
	$GLOBALS['label_otherR'] = $_label['otherR'];
	$GLOBALS['isStatic'] = true;

	$globals =  '
//Liste des variables globales
	$GLOBALS[\'label_user\'] = '.strval($_label['user']).';
	$GLOBALS[\'label_group\'] = '.strval($_label['group']).';
	$GLOBALS[\'label_id\'] = '.$_label['id'].';
	$GLOBALS[\'label_name\'] = \''.addSlashes($_label['name']).'\';
	$GLOBALS[\'label_type\'] = \''.$_label['type'].'\';
	$GLOBALS[\'label_dateC\'] = '.$_label['dateC'].';
	$GLOBALS[\'label_dateU\'] = '.$_label['dateU'].';
	$GLOBALS[\'label_userW\'] = '.$_label['userW'].';
	$GLOBALS[\'label_groupW\'] = '.$_label['groupW'].';
	$GLOBALS[\'label_otherW\'] = '.$_label['otherW'].';
	$GLOBALS[\'label_userR\'] = '.$_label['userR'].';
	$GLOBALS[\'label_groupR\'] = '.$_label['groupR'].';
	$GLOBALS[\'label_otherR\'] = '.$_label['otherR'].';
	$GLOBALS[\'isStatic\'] = false;

	
	if(!empty($_POST[\'tmpId\']))
		$GLOBALS[\'tmpId\'] = $_POST[\'tmpId\'];
	else {
		if(empty($_SESSION[\'tmpId\']))
			$_SESSION[\'tmpId\'] = 1;
		else
			$_SESSION[\'tmpId\']++;
		$GLOBALS[\'tmpId\'] = $_SESSION[\'tmpId\'];
	}';

	if($_GET['altPuZZle'] == 'true') {
	$verif = '
//On verifie que le label est accéssible en écriture
	if(!labelIsWritable()) {
		loadZzS(\'ErrorLimitedRight\');
		exit();
	}';
	}
	else {
	$verif = '
//On verifie que le label est accéssible en lecture
	if(!labelIsReadable()) {
		loadZzS(\'ErrorLimitedRight\');
		exit();
	}';
	}


	//Titre de la page
		//$labelName = $_label['name'];
		$tr = new ZzTranslation('puZZleName',null);
		$title = addslashes($tr->tr($_label['puZZleName'])).': '.addSlashes($_label['name']);
	
		if(file_exists($_infoLabel['puZZleName'])) {
		}
		else {
		}

	$return = '<?php
/*
	Fichier ZZG
	Généré le : '.date('d - m - Y').'

//On vérifie l existance des sessions
	if(!isSet($_SESSION))
		exit();'.$globals.$verif.'
?>';

	$ZzS = str_replace("\n","",$ZzS);
	$ZzS = str_replace("\r","",$ZzS);
	$php = '
$page =	new page("page");';
	$php .= '
$page->setTitle(\''.$title.'\');';
	if(isSet($noStructure) and $noStructure)
		$php .=  '
$page->setNoStructure(\'true\');';
	//$ListObject = Array('page'=>array('main'=>$Page));
	$Cursor = 0;
	$line = 1;
	$_ZzO = array();

	$length = strlen($ZzS);
	while(($instruction = convertInstruction($ZzS,$Cursor,$line, $length,$LastObjectCall, $_ZzO)) !== false)
		$php .= $instruction;

	$php .= 'echo $page->buildStaticpuZZle();';
	$php .= '
$GLOBALS[\'noCache\'] = $page->noCache;';

	ob_start();
		eval($php);
		$gen = ob_get_contents();
	ob_end_clean();
	
	//Création des pièces dynamique
		$boutDeclaration = '
<?php //Create dynamics bouts';
		if(is_array($GLOBALS['bouts']))
		foreach($GLOBALS['bouts'] as $bout) {
			$boutDeclaration .= '
	$'.$bout['name'].' = new '.$bout['bootName'].'(\''.$bout['name'].'\',null);
'.$bout['autoset'].$bout['store'].'	$'.$bout['name'].'->buildBout();';
		}
		$boutDeclaration .= '
	//Destruction of all ZzIO instances
	if(is_array($GLOBALS[\'ioInstance\']))
	foreach($GLOBALS[\'ioInstance\'] as $instance) {
		$instance->__destruct();
	}
?>';
		
	//$return .= '//$GLOBALS[\'MySql\']->close();'."\n";
/*	 $return .= '?>';
	return $return.$boutDeclaration.$gen;
	
	
	
}*/
?>